<template>
  <div class="user-detail-container">
    <t-card class="detail-card">
      <template #header>
        <div class="detail-header">
          <t-space align="center">
            <t-button theme="default" variant="outline" @click="handleBack">
              <template #icon><t-icon name="chevron-left" /></template>
              返回
            </t-button>
            <h2>用户详情</h2>
          </t-space>
          <t-space>
            <t-button v-if="canEdit" theme="primary" @click="handleEdit">
              <template #icon><t-icon name="edit" /></template>
              编辑用户
            </t-button>
            <t-dropdown v-if="canToggleStatus || canResetPassword || canDelete">
              <t-button variant="outline">
                <template #icon><t-icon name="more" /></template>
                更多操作
              </t-button>
              <t-dropdown-menu>
                <t-dropdown-item v-if="canToggleStatus" @click="handleToggleStatus">
                  <t-icon :name="userDetail.status === 1 ? 'poweroff' : 'check-circle'" />
                  {{ userDetail.status === 1 ? '禁用用户' : '启用用户' }}
                </t-dropdown-item>
                <t-dropdown-item v-if="canResetPassword" @click="handleResetPassword">
                  <t-icon name="lock-on" />
                  重置密码
                </t-dropdown-item>
                <t-dropdown-item v-if="canDelete" theme="danger" @click="handleDelete">
                  <t-icon name="delete" />
                  删除用户
                </t-dropdown-item>
              </t-dropdown-menu>
            </t-dropdown>
          </t-space>
        </div>
      </template>

      <t-loading :loading="loading">
        <div v-if="userDetail" class="detail-content">
          <!-- 基本信息 -->
          <div class="info-section">
            <h3 class="section-title">基本信息</h3>
            <t-row :gutter="24">
              <t-col :span="6">
                <div class="avatar-section">
                  <t-avatar 
                    :image="userDetail.avatar" 
                    size="80px"
                    :alt="userDetail.nickname || userDetail.username"
                  >
                    {{ (userDetail.nickname || userDetail.username)?.[0] }}
                  </t-avatar>
                  <div class="avatar-info">
                    <h4>{{ userDetail.nickname || userDetail.username }}</h4>
                    <t-tag 
                      :theme="userDetail.status === 1 ? 'success' : 'danger'"
                      variant="light"
                    >
                      {{ userDetail.status === 1 ? '正常' : '禁用' }}
                    </t-tag>
                  </div>
                </div>
              </t-col>
              <t-col :span="18">
                <t-row :gutter="24">
                  <t-col :span="12">
                    <div class="info-item">
                      <label>用户ID</label>
                      <span>{{ userDetail.id }}</span>
                    </div>
                  </t-col>
                  <t-col :span="12">
                    <div class="info-item">
                      <label>用户名</label>
                      <span>{{ userDetail.username }}</span>
                    </div>
                  </t-col>
                  <t-col :span="12">
                    <div class="info-item">
                      <label>昵称</label>
                      <span>{{ userDetail.nickname || '-' }}</span>
                    </div>
                  </t-col>
                  <t-col :span="12">
                    <div class="info-item">
                      <label>邮箱</label>
                      <span>{{ userDetail.email || '-' }}</span>
                    </div>
                  </t-col>
                  <t-col :span="12">
                    <div class="info-item">
                      <label>手机号</label>
                      <span>{{ userDetail.phone || '-' }}</span>
                    </div>
                  </t-col>
                  <t-col :span="12">
                    <div class="info-item">
                      <label>角色</label>
                      <t-space>
                        <t-tag 
                          v-for="role in userDetail.roles" 
                          :key="role.id"
                          theme="primary" 
                          variant="light"
                        >
                          {{ role.name }}
                        </t-tag>
                      </t-space>
                    </div>
                  </t-col>
                </t-row>
              </t-col>
            </t-row>
          </div>

          <!-- 时间信息 -->
          <div class="info-section">
            <h3 class="section-title">时间信息</h3>
            <t-row :gutter="24">
              <t-col :span="8">
                <div class="info-item">
                  <label>创建时间</label>
                  <span>{{ formatDateTime(userDetail.createdAt) }}</span>
                </div>
              </t-col>
              <t-col :span="8">
                <div class="info-item">
                  <label>更新时间</label>
                  <span>{{ formatDateTime(userDetail.updatedAt) }}</span>
                </div>
              </t-col>
              <t-col :span="8">
                <div class="info-item">
                  <label>最后登录</label>
                  <span>{{ formatDateTime(userDetail.lastLoginTime) }}</span>
                </div>
              </t-col>
            </t-row>
          </div>

          <!-- 操作日志 -->
          <div class="info-section">
            <h3 class="section-title">最近操作日志</h3>
            <t-table
              :data="operationLogs"
              :columns="logColumns"
              :pagination="false"
              size="small"
              stripe
            />
          </div>
        </div>
      </t-loading>
    </t-card>

    <!-- 编辑用户对话框 -->
    <UserForm 
      v-model:visible="showEditForm"
      mode="edit"
      :user-data="userDetail"
      @success="fetchUserDetail"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { useUserManagementStore } from '@/stores/userManagement'
import { usePermission } from '@/composables/usePermission'
import { USER_PERMISSIONS } from '@/utils/permission'
import UserForm from './UserForm.vue'

const route = useRoute()
const router = useRouter()
const userManagementStore = useUserManagementStore()
const { hasPermission } = usePermission()

const loading = ref(false)
const userDetail = ref(null)
const showEditForm = ref(false)

// 权限检查
const canEdit = computed(() => hasPermission(USER_PERMISSIONS.EDIT))
const canDelete = computed(() => hasPermission(USER_PERMISSIONS.DELETE))
const canResetPassword = computed(() => hasPermission(USER_PERMISSIONS.RESET_PASSWORD))
const canToggleStatus = computed(() => hasPermission(USER_PERMISSIONS.TOGGLE_STATUS))

// 操作日志数据（模拟）
const operationLogs = ref([
  {
    id: 1,
    action: '登录系统',
    ip: '192.168.1.100',
    userAgent: 'Chrome 120.0.0.0',
    createdAt: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 2,
    action: '修改个人信息',
    ip: '192.168.1.100',
    userAgent: 'Chrome 120.0.0.0',
    createdAt: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000).toISOString()
  },
  {
    id: 3,
    action: '登录系统',
    ip: '192.168.1.101',
    userAgent: 'Safari 17.0',
    createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString()
  }
])

// 日志表格列配置
const logColumns = [
  { colKey: 'action', title: '操作', width: 150 },
  { colKey: 'ip', title: 'IP地址', width: 150 },
  { colKey: 'userAgent', title: '浏览器', width: 200 },
  { 
    colKey: 'createdAt', 
    title: '操作时间',
    cell: (h, { row }) => formatDateTime(row.createdAt)
  }
]

// 获取用户详情
const fetchUserDetail = async () => {
  const userId = route.params.id
  if (!userId) {
    MessagePlugin.error('用户ID不存在')
    handleBack()
    return
  }

  loading.value = true
  try {
    const result = await userManagementStore.getUserDetail(userId)
    if (result.success) {
      userDetail.value = result.data
    } else {
      MessagePlugin.error(result.message)
      handleBack()
    }
  } catch (error) {
    MessagePlugin.error('获取用户详情失败')
    handleBack()
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 返回列表
const handleBack = () => {
  router.push('/users')
}

// 编辑用户
const handleEdit = () => {
  showEditForm.value = true
}

// 切换用户状态
const handleToggleStatus = () => {
  const newStatus = userDetail.value.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  const dialog = DialogPlugin.confirm({
    header: '确认操作',
    body: `确定要${statusText}用户 "${userDetail.value.nickname || userDetail.value.username}" 吗？`,
    confirmBtn: `确定${statusText}`,
    cancelBtn: '取消',
    onConfirm: async () => {
      const result = await userManagementStore.updateUserStatus(userDetail.value.id, newStatus)
      if (result.success) {
        MessagePlugin.success(result.message)
        fetchUserDetail()
      } else {
        MessagePlugin.error(result.message)
      }
      dialog.destroy()
    }
  })
}

// 重置密码
const handleResetPassword = () => {
  const dialog = DialogPlugin.confirm({
    header: '重置密码',
    body: `确定要重置用户 "${userDetail.value.nickname || userDetail.value.username}" 的密码吗？`,
    confirmBtn: '确定重置',
    cancelBtn: '取消',
    onConfirm: async () => {
      const result = await userManagementStore.resetUserPassword(userDetail.value.id)
      if (result.success) {
        MessagePlugin.success(`密码重置成功，新密码：${result.data.newPassword}`)
      } else {
        MessagePlugin.error(result.message)
      }
      dialog.destroy()
    }
  })
}

// 删除用户
const handleDelete = () => {
  const dialog = DialogPlugin.confirm({
    header: '确认删除',
    body: `确定要删除用户 "${userDetail.value.nickname || userDetail.value.username}" 吗？此操作不可恢复。`,
    confirmBtn: '确定删除',
    cancelBtn: '取消',
    theme: 'danger',
    onConfirm: async () => {
      const result = await userManagementStore.deleteUser(userDetail.value.id)
      if (result.success) {
        MessagePlugin.success(result.message)
        handleBack()
      } else {
        MessagePlugin.error(result.message)
      }
      dialog.destroy()
    }
  })
}

onMounted(() => {
  fetchUserDetail()
})
</script>

<style scoped>
.user-detail-container {
  height: 100%;
}

.detail-card {
  height: 100%;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.detail-header h2 {
  margin: 0;
}

.detail-content {
  padding: 0;
}

.info-section {
  margin-bottom: 32px;
}

.info-section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--td-text-color-primary);
  border-bottom: 1px solid var(--td-border-level-1-color);
  padding-bottom: 8px;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.avatar-info {
  margin-top: 12px;
}

.avatar-info h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.info-item {
  margin-bottom: 16px;
}

.info-item label {
  display: block;
  font-size: 14px;
  color: var(--td-text-color-secondary);
  margin-bottom: 4px;
  font-weight: 500;
}

.info-item span {
  font-size: 14px;
  color: var(--td-text-color-primary);
  word-break: break-all;
}

:deep(.t-table) {
  border: 1px solid var(--td-border-level-1-color);
  border-radius: var(--td-radius-default);
}
</style>
